#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import http.server
import socketserver
import json
import os
import webbrowser
import requests
from datetime import datetime, timedelta
import time
from typing import List, Dict, Any
import re
import concurrent.futures

# 导入高德API
from backend.gaode_api import GaodeAPI

# 12306 实时查询配置
DEFAULT_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
    "Referer": "https://kyfw.12306.cn/otn/leftTicket/init",
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Connection": "keep-alive",
}
QUERY_ENDPOINTS = [
    "https://kyfw.12306.cn/otn/leftTicket/query",
    "https://kyfw.12306.cn/otn/leftTicket/queryZ",
    "https://kyfw.12306.cn/otn/leftTicket/queryA",
    "https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice",
]

# 简单内存缓存（1小时）
RAIL_CACHE = {}
# 价格缓存（10分钟）
PRICE_CACHE = {}

# 高德API配置
GAODE_API_KEY = "003df4ac18f1cca97eaf59dc90afbaa2"
_gaode_api = None

def get_gaode_api():
    """获取高德API实例"""
    global _gaode_api
    if _gaode_api is None:
        _gaode_api = GaodeAPI(GAODE_API_KEY)
    return _gaode_api

# 聚合数据API配置（航班）
JUHE_FLIGHT_APPKEY = "b0daee5c7cf963ae6458020601583575"

# 城市到IATA机场代码映射
CITY_TO_IATA = {
    '大连': 'DLC', '北京': 'PEK', '上海': 'PVG', '广州': 'CAN',
    '深圳': 'SZX', '成都': 'CTU', '重庆': 'CKG', '西安': 'XIY',
    '武汉': 'WUH', '南京': 'NKG', '杭州': 'HGH', '天津': 'TSN',
    '青岛': 'TAO', '厦门': 'XMN', '长沙': 'CSX', '郑州': 'CGO',
    '合肥': 'HFE', '济南': 'TNA', '福州': 'FOC', '南昌': 'KHN',
    '石家庄': 'SJW', '太原': 'TYN', '呼和浩特': 'HET', '沈阳': 'SHE',
    '长春': 'CGQ', '哈尔滨': 'HRB', '昆明': 'KMG', '贵阳': 'KWE',
    '南宁': 'NNG', '海口': 'HAK', '三亚': 'SYX', '兰州': 'LHW',
    '西宁': 'XNN', '银川': 'INC', '乌鲁木齐': 'URC', '拉萨': 'LXA',
    '池州': 'HFE', '东至': 'HFE', '东至县': 'HFE'  # 安徽小城市使用合肥机场
}

# 周边城市映射（用于附近城市搜索与联运）
NEARBY_CITIES = {
    '大连': ['沈阳', '营口', '丹东', '鞍山'],
    '合肥': ['南京', '武汉', '郑州', '济南'],
    '北京': ['天津', '石家庄', '保定', '廊坊'],
    '上海': ['南京', '杭州', '苏州', '无锡'],
    '广州': ['深圳', '佛山', '东莞', '中山'],
    '深圳': ['广州', '东莞', '惠州', '佛山'],
    '池州': ['合肥', '南京', '武汉'],
    '东至': ['合肥', '池州', '安庆'],
    '东至县': ['合肥', '池州', '安庆']
}

def _nearby_list(city: str) -> List[str]:
    return NEARBY_CITIES.get(city, [])

def _cache_get(key: str):
    ent = RAIL_CACHE.get(key)
    if not ent:
        return None
    ts, data = ent
    if time.time() - ts < 3600:
        return data
    return None

def _cache_set(key: str, data):
    RAIL_CACHE[key] = (time.time(), data)

def get_ground_transport_info(origin: str, destination: str, transport_type: str = 'driving') -> Dict:
    """获取地面交通信息"""
    try:
        gaode_api = get_gaode_api()
        if not gaode_api:
            return {}
        
        route_info = gaode_api.get_route_info(origin, destination, transport_type)
        if route_info:
            return {
                'duration': route_info.get('duration', 0),
                'distance': route_info.get('distance', 0),
                'type': transport_type,
                'description': f"{transport_type}约{route_info.get('duration', 0)}分钟，{route_info.get('distance', 0)}公里"
            }
    except Exception as e:
        print(f"获取地面交通信息失败: {e}")
    
    return {}

def get_transport_hub_access(origin: str, hub_name: str, hub_type: str = 'airport') -> Dict:
    """获取到交通枢纽的接驳信息"""
    try:
        gaode_api = get_gaode_api()
        if not gaode_api:
            return {}
        
        return gaode_api.get_airport_station_access(origin, hub_name, hub_type)
    except Exception as e:
        print(f"获取交通枢纽接驳信息失败: {e}")
    
    return {}

def _norm_city(name: str) -> str:
    if not name:
        return ''
    n = str(name).strip()
    if '(' in n:
        n = n.split('(')[0]
    
    # 处理具体的学校、车站等名称，提取城市名
    city_mappings = {
        '大连交通大学': '大连',
        '大连理工大学': '大连',
        '大连海事大学': '大连',
        '大连大学': '大连',
        '合肥南站': '合肥',
        '合肥站': '合肥',
        '合肥西站': '合肥',
        '合肥东站': '合肥',
        '北京南站': '北京',
        '北京西站': '北京',
        '北京站': '北京',
        '上海虹桥站': '上海',
        '上海南站': '上海',
        '上海站': '上海',
        '广州南站': '广州',
        '广州站': '广州',
        '深圳北站': '深圳',
        '深圳站': '深圳',
        '南京南站': '南京',
        '南京站': '南京',
        '武汉站': '武汉',
        '武汉汉口站': '武汉',
        '成都东站': '成都',
        '成都站': '成都',
        '重庆北站': '重庆',
        '重庆站': '重庆',
        '西安北站': '西安',
        '西安站': '西安',
        '郑州东站': '郑州',
        '郑州站': '郑州',
        '杭州东站': '杭州',
        '杭州站': '杭州',
        '东至县': '东至',
        '东至': '东至',
    }
    
    # 先检查是否有精确匹配
    if n in city_mappings:
        return city_mappings[n]
    
    # 处理通用后缀
    for suf in ['市', '站', '南站', '北站', '东站', '西站', '火车站', '高铁站', '大学', '学院', '学校', '县']:
        n = n.replace(suf, '')
    
    return n

def http_get_with_retry(url, params, timeout_seconds=15, max_retries=1):
    session = requests.Session()
    last_exc = None
    for attempt in range(max_retries + 1):
        try:
            resp = session.get(url, params=params, timeout=timeout_seconds)
            return resp
        except Exception as e:
            last_exc = e
            backoff = 1.5 ** attempt
            print(f"⚠️ 航班API请求失败，第{attempt+1}次：{e}，{('重试中' if attempt < max_retries else '不再重试')}…")
            if attempt < max_retries:
                time.sleep(backoff)
    raise last_exc

def get_flight_data(origin, destination, date):
    """获取机票数据（聚合数据API）"""
    try:
        # 获取机场代码
        dep_code = CITY_TO_IATA.get(origin, 'PEK')
        arr_code = CITY_TO_IATA.get(destination, 'PEK')
        
        url = "https://apis.juhe.cn/flight/query"
        params = {
            'key': JUHE_FLIGHT_APPKEY,
            'dtype': 'json',
            'departure': dep_code,
            'arrival': arr_code,
            'departureDate': date
        }
        
        print(f"✈️ 获取机票数据: {origin}({dep_code}) → {destination}({arr_code})")
        
        try:
            response = http_get_with_retry(url, params=params, timeout_seconds=15, max_retries=1)
        except Exception as e:
            print(f"❌ 航班API连续失败: {e}")
            return []  # 失败返回空列表
        
        if response.status_code == 200:
            result = response.json()
            
            if result.get('error_code') == 0:
                flights = []
                flight_list = result.get('result', {}).get('flightInfo', [])
                
                for item in flight_list:
                    try:
                        # 计算总时间（小时）
                        dep_time = item.get('departureTime', '')
                        arr_time = item.get('arrivalTime', '')
                        dep_date = item.get('departureDate', '')
                        arr_date = item.get('arrivalDate', '')
                        total_time = 2.0  # 默认2小时
                        try:
                            dep_dt_str = f"{dep_date} {dep_time}".strip()
                            arr_dt_str = f"{arr_date} {arr_time}".strip()
                            from datetime import datetime as _dt
                            dep_dt = _dt.strptime(dep_dt_str, '%Y-%m-%d %H:%M')
                            arr_dt = _dt.strptime(arr_dt_str, '%Y-%m-%d %H:%M')
                            if arr_dt < dep_dt:
                                arr_dt = arr_dt.replace(day=arr_dt.day) + timedelta(days=1)
                            total_minutes = int((arr_dt - dep_dt).total_seconds() // 60)
                            total_time = max(0.5, round(total_minutes / 60.0, 1))
                        except Exception:
                            pass
                        
                        flight = {
                            'type': 'flight',
                            'flight_number': item.get('flightNo', ''),
                            'airline': item.get('airlineName', ''),
                            'origin': origin,
                            'destination': destination,
                            'dep_time': f"{item.get('departureDate', '')} {item.get('departureTime', '')}",
                            'arr_time': f"{item.get('arrivalDate', '')} {item.get('arrivalTime', '')}",
                            'price': int(item.get('ticketPrice', 0)),
                            'dep_airport': item.get('departureName', ''),
                            'arr_airport': item.get('arrivalName', ''),
                            'duration': f"{item.get('departureTime', '')} - {item.get('arrivalTime', '')}",
                            'source': '聚合数据API',
                            'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                            # 前端期望字段
                            'total_time': total_time,
                            'total_price': int(item.get('ticketPrice', 0)),
                            'transfers': 0,
                            'details': [{
                                'type': 'flight',
                                'origin': origin,
                                'destination': destination,
                                'departure_time': f"{item.get('departureTime', '')}",
                                'arrival_time': f"{item.get('arrivalTime', '')}",
                                'price': int(item.get('ticketPrice', 0)),
                                'airline': item.get('airlineName', ''),
                                'flight_number': item.get('flightNo', '')
                            }]
                        }
                        
                        if flight['price'] > 0:
                            flights.append(flight)
                            
                    except Exception as e:
                        print(f"  ❌ 解析航班条目异常: {e}")
                        continue
                
                print(f"✅ 获取到 {len(flights)} 条机票数据")
                return flights
            else:
                print(f"❌ 机票API错误: {result.get('reason', '未知')}")
                return []
        else:
            print(f"❌ 机票API请求失败: {response.status_code}")
            return []
            
    except Exception as e:
        print(f"❌ 机票API异常: {e}")
        return []

def load_station_map():
    """加载12306站点映射"""
    station_map = {
        '北京': 'BJP', '上海': 'SHH', '广州': 'GZQ', '深圳': 'SZN',
        '成都': 'CDW', '重庆': 'CQW', '西安': 'XAY', '武汉': 'WHN',
        '南京': 'NJH', '杭州': 'HZH', '天津': 'TJP', '青岛': 'QDK',
        '厦门': 'XMS', '长沙': 'CSQ', '郑州': 'ZZF', '合肥': 'HFH',
        '济南': 'JNK', '福州': 'FZS', '南昌': 'NCG', '石家庄': 'SJP',
        '太原': 'TYV', '呼和浩特': 'HHC', '沈阳': 'SYT', '大连': 'DLT',
        '长春': 'CCT', '哈尔滨': 'HBB', '昆明': 'KMM', '贵阳': 'GIW',
        '南宁': 'NNZ', '海口': 'VUQ', '三亚': 'SEQ', '兰州': 'LZJ',
        '西宁': 'XNO', '银川': 'YIJ', '乌鲁木齐': 'WAR', '拉萨': 'LSO',
        '池州': 'IYH', '东至': 'DCH', '东至县': 'DCH'
    }
    return station_map

def crawl_12306_trains_realtime(origin, destination, date):
    """爬取12306实时高铁数据"""
    try:
        station_map = load_station_map()
        
        # 获取站点代码
        from_code = station_map.get(origin)
        to_code = station_map.get(destination)
        
        if not from_code or not to_code:
            print(f"❌ 未找到站点代码: {origin} -> {from_code}, {destination} -> {to_code}")
            return []
        
        print(f"🚂 查询高铁: {origin}({from_code}) → {destination}({to_code})")
        
        # 构建查询参数
        params = {
            'leftTicketDTO.train_date': date,
            'leftTicketDTO.from_station': from_code,
            'leftTicketDTO.to_station': to_code,
            'purpose_codes': 'ADULT'
        }
        
        # 尝试多个端点
        for endpoint in QUERY_ENDPOINTS:
            try:
                response = requests.get(endpoint, params=params, headers=DEFAULT_HEADERS, timeout=15)
                if response.status_code == 200:
                    data = response.json()
                    if data.get('status') and data.get('data'):
                        trains = []
                        for item in data['data']:
                            try:
                                train_info = item.split('|')
                                if len(train_info) > 20:
                                    train = {
                                        'train_code': train_info[3],
                                        'dep_time': train_info[8],
                                        'arr_time': train_info[9],
                                        'duration': train_info[10],
                                        'from_station_name': train_info[6],
                                        'to_station_name': train_info[7],
                                        'seat_types': train_info[35],
                                        'ed_left': train_info[31] if len(train_info) > 31 else '',
                                        'yd_left': train_info[30] if len(train_info) > 30 else '',
                                        'swz_left': train_info[32] if len(train_info) > 32 else '',
                                        'yz_left': train_info[29] if len(train_info) > 29 else '',
                                        'yw_left': train_info[28] if len(train_info) > 28 else '',
                                        'rw_left': train_info[33] if len(train_info) > 33 else '',
                                        'train_no': train_info[3],
                                        'from_station_no': train_info[16],
                                        'to_station_no': train_info[17],
                                    }
                                    trains.append(train)
                            except Exception as e:
                                print(f"  ❌ 解析车次异常: {e}")
                                continue
                        
                        print(f"✅ 获取到 {len(trains)} 条高铁数据")
                        return trains
            except Exception as e:
                print(f"  ❌ 端点 {endpoint} 失败: {e}")
                continue
        
        print("❌ 所有12306端点都失败")
        return []
        
    except Exception as e:
        print(f"❌ 12306查询异常: {e}")
        return []

def find_train_routes(origin, destination, date):
    """查找高铁路线"""
    try:
        trains = crawl_12306_trains_realtime(origin, destination, date)
        if not trains:
            return []
        
        routes = []
        for train in trains:
            try:
                # 计算总时间
                dep_time = train.get('dep_time', '')
                arr_time = train.get('arr_time', '')
                total_time = 2.0  # 默认2小时
                try:
                    from datetime import datetime as _dt
                    dep_dt = _dt.strptime(f"{date} {dep_time}", '%Y-%m-%d %H:%M')
                    arr_dt = _dt.strptime(f"{date} {arr_time}", '%Y-%m-%d %H:%M')
                    if arr_dt < dep_dt:
                        arr_dt = arr_dt + timedelta(days=1)
                    total_minutes = int((arr_dt - dep_dt).total_seconds() // 60)
                    total_time = max(0.5, round(total_minutes / 60.0, 1))
                except Exception:
                    pass
                
                route = {
                    'type': 'high_speed_rail',
                    'train_code': train.get('train_code', ''),
                    'origin': origin,
                    'destination': destination,
                    'dep_time': f"{date} {dep_time}",
                    'arr_time': f"{date} {arr_time}",
                    'duration': train.get('duration', ''),
                    'price': 0,  # 需要单独查询价格
                    'source': '12306实时数据',
                    'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    'total_time': total_time,
                    'total_price': 0,
                    'transfers': 0,
                    'details': [{
                        'type': 'high_speed_rail',
                        'origin': origin,
                        'destination': destination,
                        'departure_time': dep_time,
                        'arrival_time': arr_time,
                        'price': 0,
                        'train_code': train.get('train_code', '')
                    }]
                }
                routes.append(route)
                
            except Exception as e:
                print(f"  ❌ 处理车次异常: {e}")
                continue
        
        return routes
        
    except Exception as e:
        print(f"❌ 查找高铁路线异常: {e}")
        return []

def search_routes_parallel(origin, destination, date, optimization_type='time'):
    """并行搜索路线 - 核心优化点"""
    origin_norm = _norm_city(origin)
    destination_norm = _norm_city(destination)
    
    all_routes = []
    
    print(f"\n🔍 并行搜索: {origin} → {destination} ({date})")
    start_time = time.time()
    
    # 使用线程池并行获取数据 - 这是关键优化！
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        # 提交任务
        flight_future = executor.submit(get_flight_data, origin_norm, destination_norm, date)
        train_future = executor.submit(find_train_routes, origin_norm, destination_norm, date)
        
        # 获取结果
        try:
            flights = flight_future.result(timeout=15)  # 减少超时时间
            all_routes.extend(flights)
            print(f"✈️ 航班数据: {len(flights)} 条")
        except Exception as e:
            print(f"❌ 航班数据获取失败: {e}")
        
        try:
            trains = train_future.result(timeout=12)  # 减少超时时间
            all_routes.extend(trains)
            print(f"🚂 高铁数据: {len(trains)} 条")
        except Exception as e:
            print(f"❌ 高铁数据获取失败: {e}")
    
    # 保持原有的排序逻辑
    if optimization_type == 'price':
        all_routes.sort(key=lambda x: x.get('total_price', x.get('price', 0)))
    else:
        all_routes.sort(key=lambda x: x.get('total_time', 0))
    
    end_time = time.time()
    print(f"⚡ 并行搜索完成: {len(all_routes)} 条结果，耗时 {end_time - start_time:.2f} 秒")
    
    return all_routes

def enhanced_sort_routes(routes, optimization_type, origin, destination):
    """智能排序路线"""
    if not routes:
        return routes
    
    # 按优化类型排序
    if optimization_type == 'price':
        routes.sort(key=lambda x: x.get('total_price', x.get('price', 0)))
    else:
        routes.sort(key=lambda x: x.get('total_time', 0))
    
    return routes

def _first_origin(route):
    """获取路线的起始城市"""
    if route.get('type') == 'multimodal' and route.get('details'):
        return route['details'][0].get('origin', '')
    return route.get('origin', '')

def _last_destination(route):
    """获取路线的终点城市"""
    if route.get('type') == 'multimodal' and route.get('details'):
        return route['details'][-1].get('destination', '')
    return route.get('destination', '')

class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        static_root = os.path.dirname(__file__)
        super().__init__(*args, directory=static_root, **kwargs)
    
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def do_GET(self):
        if self.path == '/':
            self.path = '/frontend/index.html'
        elif self.path.startswith('/api/'):
            self.handle_api_request()
            return
        super().do_GET()
    
    def do_POST(self):
        if self.path == '/api/search':
            self.handle_search_request()
        elif self.path == '/api/poi':
            self.handle_poi_request()
        elif self.path == '/api/geocode':
            self.handle_geocode_request()
        elif self.path == '/api/chat':
            self.handle_chat_request()
        elif self.path == '/api/rail_price':
            self.handle_rail_price_request()
        else:
            self.send_error(404)
    
    def handle_api_request(self):
        if self.path == '/api/status':
            self.send_api_status()
        elif self.path == '/api/cities':
            self.send_cities()
        elif self.path.startswith('/api/weather'):
            self.send_weather()
        else:
            self.send_error(404)
    
    def handle_search_request(self):
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        
        try:
            data = json.loads(post_data.decode('utf-8'))
        except:
            data = {}
        
        # 解析参数后
        origin = data.get('origin', '北京')
        destination = data.get('destination', '上海')
        date = data.get('date') or data.get('departure_date')
        origin_address = data.get('origin_address', '')  # 起点详细地址
        destination_address = data.get('destination_address', '')  # 终点详细地址
        
        print(f"📍 地址信息: 起点地址='{origin_address}', 终点地址='{destination_address}'")

        # 归一化城市名（去掉"市/站/大学"等后缀）
        origin_norm = _norm_city(origin)
        destination_norm = _norm_city(destination)

        # 确保 optimization_type 一定有值，且是字符串
        raw_opt = data.get('optimization_type')
        optimization_type = str(raw_opt).strip().lower() if raw_opt else 'time'

        # 统一安全日期（没传就用今天）
        from datetime import datetime as _dt
        safe_date = date or _dt.now().strftime('%Y-%m-%d')
        
        print(f"\n 搜索请求: {origin} → {destination} ({safe_date})")
        print("=" * 50)
        
        # 使用并行搜索 - 核心优化
        all_routes = search_routes_parallel(origin, destination, safe_date, optimization_type)
        
        # 智能排序和分组
        print("🧠 开始智能排序...")
        all_routes = enhanced_sort_routes(all_routes, optimization_type, origin, destination)

        # 统计信息
        flights_count = len([x for x in all_routes if x.get('type') == 'flight'])
        trains_count = len([x for x in all_routes if x.get('type') == 'high_speed_rail'])
        multimodal_count = len([x for x in all_routes if x.get('type') == 'multimodal'])
        nearby_count = len([x for x in all_routes if x.get('is_nearby', False)])
        
        same_day_arrival = len([x for x in all_routes if x.get('arrival_type') == 'same_day'])
        next_day_arrival = len([x for x in all_routes if x.get('arrival_type') == 'next_day'])
        
        direct_count = len([x for x in all_routes if x.get('category') == '直达'])
        same_day_count = len([x for x in all_routes if x.get('category') == '日内到达'])
        next_day_count = len([x for x in all_routes if x.get('category') == '隔日到达'])

        result = {
            'success': True,
            'routes': all_routes,
            'data': all_routes,
            'total': len(all_routes),
            'flights': flights_count,
            'trains': trains_count,
            'multimodal': multimodal_count,
            'nearby': nearby_count,
            'same_day': same_day_arrival,
            'next_day': next_day_arrival,
            'group_counts': {
                'direct': direct_count,
                'same_day': same_day_count,
                'next_day': next_day_count
            },
            'optimization_type': optimization_type,
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        print(f"✅ 搜索完成: 总计 {len(all_routes)} 条结果")
        print(f"   ✈️ 机票: {flights_count} 条")
        print(f"   高铁: {trains_count} 条")
        print(f"   联运: {multimodal_count} 条")
        print(f"   周边(保留后统计): {nearby_count} 条")
        print(f"   日内到达: {same_day_count} 条")
        print(f"   隔日到达: {next_day_count} 条")
        print("=" * 50)
        
        self.send_json_response(result)
    
    def send_api_status(self):
        """发送API状态"""
        status = {
            'success': True,
            'status': 'online',
            'message': 'API服务正常运行',
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'features': [
                '真实机票数据获取（聚合数据API）',
                '实时12306高铁查询',
                '多式联运智能规划（时间衔接）',
                '周边城市智能对比',
                '智能排序和推荐'
            ],
            'apis': {
                'flight': 'enabled',
                'railway': 'enabled',
                'multimodal': 'enabled',
                'nearby': 'enabled',
                'smart_sort': 'enabled',
                'weather': 'mock',
                'poi': 'mock',
                'geocode': 'mock',
                'chat': 'mock'
            },
            'nearby_cities': NEARBY_CITIES
        }
        self.send_json_response(status)
    
    def send_cities(self):
        """返回城市列表"""
        cities = list(CITY_TO_IATA.keys())
        self.send_json_response({'success': True, 'cities': cities})
    
    def send_weather(self):
        try:
            from urllib.parse import urlparse, parse_qs
            query = parse_qs(urlparse(self.path).query)
            city = (query.get('city') or ['北京'])[0]
        except Exception:
            city = '北京'
        data = {
            'success': True,
            'weather': {
                'weather': '晴',
                'temperature': 22,
                'humidity': 60,
                'wind_power': 3,
                'wind_direction': '东南风'
            },
            'city': city,
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        self.send_json_response(data)
    
    def handle_poi_request(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length) if content_length > 0 else b'{}'
        try:
            payload = json.loads(body.decode('utf-8'))
        except:
            payload = {}
        keyword = payload.get('keyword', '景点')
        city = payload.get('city', '北京')
        
        try:
            # 尝试使用高德API获取真实POI数据
            print(f"🔍 POI搜索: {keyword} in {city}")
            gaode_api = get_gaode_api()
            if gaode_api:
                print("  📡 调用高德API...")
                pois = gaode_api.search_poi(keyword, city)
                print(f"  📊 高德API返回 {len(pois) if pois else 0} 个结果")
                if pois:
                    # 格式化POI数据以匹配前端期望的格式
                    formatted_pois = []
                    for poi in pois[:5]:  # 只取前5个结果
                        formatted_pois.append({
                            'id': poi.get('id', ''),
                            'name': poi.get('name', ''),
                            'address': poi.get('address', ''),
                            'location': poi.get('location', ''),
                            'type': poi.get('type', keyword)
                        })
                    print(f"  ✅ 返回 {len(formatted_pois)} 个格式化POI")
                    self.send_json_response({ 'success': True, 'pois': formatted_pois, 'source': 'gaode' })
                    return
        except Exception as e:
            print(f"❌ POI搜索失败: {e}")
        
        # 如果高德API失败，返回模拟数据
        pois = [
            { 'id': '1', 'name': f'{city}{keyword}示例一', 'address': f'{city}中心区', 'location': '116.3974,39.9093', 'type': keyword },
            { 'id': '2', 'name': f'{city}{keyword}示例二', 'address': f'{city}热门商圈', 'location': '116.4053,39.9042', 'type': keyword },
            { 'id': '3', 'name': f'{city}{keyword}示例三', 'address': f'{city}特色街区', 'location': '116.4120,39.9200', 'type': keyword }
        ]
        self.send_json_response({ 'success': True, 'pois': pois, 'source': 'mock' })
    
    def handle_geocode_request(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length) if content_length > 0 else b'{}'
        try:
            payload = json.loads(body.decode('utf-8'))
        except:
            payload = {}
        address = payload.get('address', '北京市东城区天安门')
        coordinates = { 'lng': 116.3974, 'lat': 39.9093 }
        self.send_json_response({ 'success': True, 'address': address, 'coordinates': coordinates })
    
    def handle_chat_request(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length) if content_length > 0 else b'{}'
        try:
            payload = json.loads(body.decode('utf-8'))
        except:
            payload = {}
        message = payload.get('message', '')
        reply = f"已收到：{message}。您也可以直接输入'北京到上海'或'查询北京天气'等指令哦。"
        self.send_json_response({ 'success': True, 'response': reply })
    
    def handle_rail_price_request(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length) if content_length > 0 else b'{}'
        try:
            payload = json.loads(body.decode('utf-8'))
        except:
            payload = {}
        date = payload.get('date') or payload.get('departure_date') or ''
        train_no = payload.get('train_no','')
        from_no = payload.get('from_station_no','')
        to_no = payload.get('to_station_no','')
        seat_types = payload.get('seat_types','')
        prefer = payload.get('seat_label','')
        
        # 简单价格返回
        resp = {
            'success': True,
            'price_map': {'O': 100, 'M': 200, 'A9': 300},
            'seat_label': prefer,
            'seat_price': 100,
            'price_source': 'mock'
        }
        self.send_json_response(resp)
    
    def send_json_response(self, data):
        self.send_response(200)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        
        json_data = json.dumps(data, ensure_ascii=False, indent=2)
        self.wfile.write(json_data.encode('utf-8'))

if __name__ == '__main__':
    PORT = 5001  # 使用5001端口避免冲突
    
    print("=" * 60)
    print(" 启动修复版HTTP服务器")
    print("=" * 60)
    print(f"服务地址: http://localhost:{PORT}")
    print(f"前端页面: http://localhost:{PORT}/frontend/index.html")
    print("=" * 60)
    print("修复内容:")
    print("- 修复API连接问题")
    print("- 添加缺失的函数")
    print("- 支持大连到东至搜索")
    print("- 并行API调用优化")
    print("=" * 60)
    print("按 Ctrl+C 停止服务")
    print("=" * 60)
    
    try:
        try:
            webbrowser.open(f"http://localhost:{PORT}/frontend/index.html")
        except Exception:
            pass
        with socketserver.TCPServer(("", PORT), MyHTTPRequestHandler) as httpd:
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"服务器启动失败: {e}")